package com.example.androidproject.my;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.fragment.app.Fragment;

import com.example.androidproject.databinding.FragmentMyBinding;
import com.example.androidproject.sqlite.UserRepository;
import com.google.gson.Gson;

//我的
public class MyFragment extends Fragment {
    private FragmentMyBinding binding;
    private WebView webView;
    private SharedPreferences sharedPreferences;
    private static final String PREF_KEY_FORM_DATA = "form_data";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentMyBinding.inflate(inflater, container, false);
        webView = binding.webview;
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        // Enable JavaScript if needed
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //获取
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        String userJson = sharedPreferences.getString("user", null);
        Gson gson = new Gson();
        UserRepository.User user = gson.fromJson(userJson, UserRepository.User.class);
        Log.e("???", "onCreateView: "+user );

        // Load HTML content
        String htmlContent = "<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>用户基本信息</title>\n" +
                "    <style>\n" +
                "        body {\n" +
                "            font-family: Arial, sans-serif;\n" +
                "            background-color: #f4f4f4;\n" +
                "            margin: 0;\n" +
                "            padding: 0;\n" +
                "        }\n" +
                "        .container {\n" +
                "            max-width: 600px;\n" +
                "            margin: 50px auto;\n" +
                "            padding: 20px;\n" +
                "            background: #fff;\n" +
                "            border-radius: 8px;\n" +
                "            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n" +
                "        }\n" +
                "        h1 {\n" +
                "            text-align: center;\n" +
                "            color: #333;\n" +
                "        }\n" +
                "        .info {\n" +
                "            margin-bottom: 15px;\n" +
                "        }\n" +
                "        .info label {\n" +
                "            font-weight: bold;\n" +
                "            color: #555;\n" +
                "            display: block;\n" +
                "            margin-bottom: 5px;\n" +
                "        }\n" +
                "        .info input, .info textarea, .info select {\n" +
                "            width: 100%;\n" +
                "            padding: 8px;\n" +
                "            border: 1px solid #ccc;\n" +
                "            border-radius: 4px;\n" +
                "            box-sizing: border-box;\n" +
                "        }\n" +
                "        .info textarea {\n" +
                "            resize: vertical;\n" +
                "            height: 100px;\n" +
                "        }\n" +
                "        .button-container {\n" +
                "            text-align: center;\n" +
                "        }\n" +
                "        .button-container button {\n" +
                "            padding: 10px 20px;\n" +
                "            margin: 5px;\n" +
                "            border: none;\n" +
                "            border-radius: 4px;\n" +
                "            cursor: pointer;\n" +
                "        }\n" +
                "        .button-container .edit-button {\n" +
                "            background-color: #4CAF50;\n" +
                "            color: white;\n" +
                "        }\n" +
                "        .button-container .save-button {\n" +
                "            background-color: #2196F3;\n" +
                "            color: white;\n" +
                "        }\n" +
                "        .button-container .edit-button:disabled {\n" +
                "            background-color: #ccc;\n" +
                "            cursor: not-allowed;\n" +
                "        }\n" +
                "    </style>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <div class=\"container\">\n" +
                "        <h1>我的信息</h1>\n" +
                "        <form id=\"userForm\">\n" +
                "            <div class=\"info\">\n" +
                "                <label for=\"name\">用户名:</label>\n" +
                "                <input type=\"text\" id=\"name\" name=\"name\" value=\""+user.getUsername()+"\" readonly>\n" +
                "            </div>\n" +
                "            <div class=\"info\">\n" +
                "                <label for=\"gender\">性别:</label>\n" +
                "                <select id=\"gender\" name=\"gender\" readonly>\n" +
                "                    <option value=\"男\">男</option>\n" +
                "                    <option value=\"女\">女</option>\n" +
                "                </select>\n" +
                "            </div>\n" +
                "            <div class=\"info\">\n" +
                "                <label for=\"address\">地址:</label>\n" +
                "                <textarea id=\"address\" name=\"address\" readonly>北京市朝阳区某街道</textarea>\n" +
                "            </div>\n" +
                "            <div class=\"info\">\n" +
                "                <label for=\"ipAddress\">本机IP地址:</label>\n" +
                "                <input type=\"text\" id=\"ipAddress\" name=\"ipAddress\" value=\""+user.getUserIp()+"\" readonly>\n" +
                "            </div>\n" +
                "            <div class=\"button-container\">\n" +
                "                <button type=\"button\" id=\"editButton\" class=\"edit-button\">编辑</button>\n" +
                "                <button type=\"submit\" id=\"saveButton\" class=\"save-button\" disabled>保存</button>\n" +
                "            </div>\n" +
                "        </form>\n" +
                "    </div>\n" +
                "\n" +
                "    <script>\n" +
                "        const editButton = document.getElementById('editButton');\n" +
                "        const saveButton = document.getElementById('saveButton');\n" +
                "        const formElements = document.querySelectorAll('#userForm input, #userForm textarea, #userForm select');\n" +
                "\n" +
                "        editButton.addEventListener('click', () => {\n" +
                "            // Enable all form elements for editing\n" +
                "            formElements.forEach(element => element.removeAttribute('readonly'));\n" +
                "            // Enable the Save button and disable the Edit button\n" +
                "            saveButton.disabled = false;\n" +
                "            editButton.disabled = true;\n" +
                "        });\n" +
                "\n" +
                "        document.getElementById('userForm').addEventListener('submit', (event) => {\n" +
                "            event.preventDefault(); // Prevent the default form submission\n" +
                "            // Here you would handle form submission logic (e.g., saving data to a server)\n" +
                "            // For demonstration, we'll just alert the user\n" +
                "            alert('信息已保存！');\n" +
                "            // Disable editing after saving\n" +
                "            formElements.forEach(element => element.setAttribute('readonly', true));\n" +
                "            // Disable the Save button and enable the Edit button\n" +
                "            saveButton.disabled = true;\n" +
                "            editButton.disabled = false;\n" +
                "        });\n" +
                "\n" +
                "        function getFormData() {\n" +
                "            const formElements = document.querySelectorAll('#userForm input, #userForm textarea, #userForm select');\n" +
                "            let formData = {};\n" +
                "            formElements.forEach(element => {\n" +
                "                formData[element.id] = element.value;\n" +
                "            });\n" +
                "            return JSON.stringify(formData);\n" +
                "        }\n" +
                "        function setFormData(data) {\n" +
                "            const formData = JSON.parse(data);\n" +
                "            for (const [key, value] of Object.entries(formData)) {\n" +
                "                const element = document.getElementById(key);\n" +
                "                if (element) {\n" +
                "                    element.value = value;\n" +
                "                }\n" +
                "            }\n" +
                "        }\n" +
                "        function fetchIpAddress() {\n" +
                "            fetch('https://api.ipify.org?format=json')\n" +
                "                .then(response => response.json())\n" +
                "                .then(data => {\n" +
                "                    document.getElementById('ipAddress').value = data.ip;\n" +
                "                });\n" +
                "        }\n" +
                "        fetchIpAddress();\n" +
                "    </script>\n" +
                "</body>\n" +
                "</html>";

        // Load the HTML content into the WebView
        webView.loadDataWithBaseURL(null, htmlContent, "text/html", "UTF-8", null);
        // Add JavaScript interface
        webView.addJavascriptInterface(new WebAppInterface(), "Android");

        // Ensure WebView has finished loading before enabling JavaScript interface
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // Load form data once the page has finished loading
                view.evaluateJavascript("setFormData(Android.getFormData());", null);
            }
        });

        return binding.getRoot();
    }

    private class WebAppInterface {
        @JavascriptInterface
        public void saveFormData(String data) {
            Log.d("WebAppInterface", "Saving form data: " + data);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(PREF_KEY_FORM_DATA, data);
            editor.apply();
        }

        @JavascriptInterface
        public String getFormData() {
            String data = sharedPreferences.getString(PREF_KEY_FORM_DATA, "{}");
            Log.d("WebAppInterface", "Getting form data: " + data);
            return data;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.evaluateJavascript("setFormData(Android.getFormData());", null);
    }

    @Override
    public void onPause() {
        super.onPause();
        webView.evaluateJavascript("Android.saveFormData(getFormData());", null);
    }
}


